package cn.itcast.erp.service.impl;

import cn.itcast.erp.dao.MenuMapper;
import cn.itcast.erp.entity.Menu;
import cn.itcast.erp.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建人: 武奇
 * 创建事件: 2019/6/3
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findByEmpId(Long uuid) {
        List<Menu> menus = getMenus2(uuid);
        return menus;
    }

    private List<Menu> getMenus2(Long uuid) {
        List<Menu> menus = this.menuMapper.findAllByEmpId(uuid);
        Menu root = menus.remove(0);
        formatList2Tree(root, menus);
        return root.getMenus();
    }

    private void formatList2Tree(Menu root, List<Menu> menus) {
        if (menus == null || menus.size() == 0) {
            return;
        }
        root.setMenus(new ArrayList<Menu>());
        for (int i = 0; i < menus.size(); i++) {
            Menu child = menus.get(i);
            if (child.getPid().equals(root.getMenuid())) {
                root.getMenus().add(menus.remove(i--));
            }
        }
        for (Menu menu : root.getMenus()) {
            if (menus.size() > 0) {
                formatList2Tree(menu, menus);
            }
        }

    }

    private List<Menu> getMenus1(Long uuid) {
        List<Menu> menus = this.menuMapper.findChildrenByPid(uuid, "0");
        queryAll(uuid, menus);
        return menus;
    }

    private void queryAll(Long empId, List<Menu> menus) {
        for (Menu menu : menus) {
            String menuid = menu.getMenuid();
            List<Menu> children = this.menuMapper.findChildrenByPid(empId, menuid);
            if (children != null && children.size() > 0) {
                menu.setMenus(children);
                queryAll(empId, children);
            }
        }
    }
}
